/*v1.04 2017-05-15*/
ISMOBILE = function(){
    var e = $(document).width()<1024;
    return e;
};
ISTEL = function(tel){
    var reg = /^1\d{10}$/;
    return reg.test(tel);
};
ISEMAIL = function(email){
    var reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    return reg.test(email);
};
GET = function (name){
    var result = location.search.match(new RegExp("[\?\&]" + name+ "=([^\&]+)","i"));
    if(result == null || result.length < 1){
        return "";
    }
    return decodeURI(result[1]);
};
COOKIE = {
    value:null,
    init:function(){
        this.value = {};
        var c = document.cookie.split(";")
        for(var i in c){
            var v = c[i].split("=");
            COOKIE.value[v[0].replace(" ","")] = v[1];
        }
    },
    get:function(k){
        if(!COOKIE.value[k]) return null;
        return unescape(COOKIE.value[k]);
    },
    set:function(key,content,second){
        // console.log(key,content);
        if(!key) return false;
        if(!content){this.delete(key);return;};
        if(!second) second = 7*24*60*60;
        var exp = new Date();
        exp.setTime(exp.getTime() + second*1000);
        if(typeof(content) == 'object') content = JSON.stringify(content);
        document.cookie = key + "="+ escape(content) + ";expires=" + exp.toGMTString();
        this.init();
    },
    delete:function(key){
        this.set(key,1,-1);
    }
};
LANG = {
    init:function(){
        langIsZh = true;
        // this.apply();
        if(langIsZh) return;
        $(document).on('bc-page-success bc-view-success',function(event) {
            LANG.apply();
        });
    },
    apply:function(){
        if(COOKIE.get('langIsNotZh')){
            langIsZh = false;
        }else{
            langIsZh = navigator.language.indexOf('zh') > -1;
        }
        $(".hidden-zh,.hidden-en").removeClass('hidden');
        if(langIsZh){
            $(".hidden-zh").addClass('hidden');
        }else{
            var lang = "en"
            $("[lang-"+lang+"]").each(function(index, el) {
                var e = $(el)
                var trans = e.attr("lang-"+lang);
                if(!trans) return true;
                if(e.attr("placeholder")){
                    e.attr('placeholder',trans);
                }else if(e.attr("type")=="submit"){
                    e.val(trans);
                    e.html(trans)
                }else{
                    e.html(trans)
                }
            });
            $(".hidden-en").addClass('hidden');
        }
    },
    setEnglish:function(){
        COOKIE.set('langIsNotZh',1);
        this.apply();
    },
    setChinese:function(){
        COOKIE.delete('langIsNotZh');
        location.reload();
    },
};
ERROR = {
    top:function(action,errormsg){
        var $tooltips = $('.js_tooltips');
        if(!$tooltips || !$tooltips.length){
            $('body').prepend("<div class='weui-toptips weui-toptips_warn js_tooltips'></div>");
            $tooltips = $('.js_tooltips');
        }
        $tooltips.css('display', 'none');
        $tooltips.fadeToggle();
        $tooltips.fadeIn();
        if(action == "0"){
            var text = "没有网络";
        }else{
            var text = action || "";
            if(action){ text+=langIsZh?"失败:":" error:"}
                text += errormsg;
        }
        $tooltips.html(text);
        var i = parseInt( $tooltips.attr("data-index") || 0 ) + 1 ;
        $tooltips.attr("data-index",i);
        setTimeout(function () {
            var ii = parseInt( $tooltips.attr("data-index") || 0 ) ;
            if( ii != i ) return;
            $tooltips.css('display', 'block');
            $tooltips.fadeOut();
        }, 3000);
    }
};
VALUE = {
    loading:function(t,key){
        if(!t || !t.length){
            return;
        }
        t.find("["+key+"]").each(function(index, el) {
            var e = $(el);
            var tag = e[0].tagName.toLowerCase();
            if(tag == 'input' || tag == 'textarea' || tag == 'select'){
                e.after("<i class='weui-loading'></i>");
                e.hide();
                return
            }
            switch(e.attr(key)){
                case "r":
                e.children().hide();
                e.children().first().siblings().remove();
                case "i":
                e.children().hide();
                e.append("<i class='weui-loading'></i>");
                break;
                case "none":
                case "d":
                e.addClass('hidden');
                break;
                default:
                e.html("<i class='weui-loading'></i>");
                break;
            }
        });
    },
    write:function(e,key,v){
        $(e).each(function(index, el) {
            VALUE._write($(el),key,v);
        });
    },
    _write:function(e,key,v){
        if(!e || !e.length){
            return;
        }
        if(v == null || v == 'null') v = "";
        var tag = e[0].tagName.toLowerCase();
        if(tag == 'input' || tag == 'textarea' || tag == 'select'){
            switch(e.attr("type")){
                case "checkbox":
                var c = v;
                if(c == "0") c = false;
                e.prop("checked",c)
                break;
                case "radio":
                e.prop("checked",(e.val() == v))
                break;
                default:
                e.val(v);
                if(tag=='select'){
                    e.attr('value',v)
                }
                // console.log(e,e.val(),v);
                // console.log(e,e.val(),v);
                // console.log(e,e.val(),v);
            }
            e.fadeIn();
            e.siblings('.weui-loading').remove();
            e.trigger('bc-value-write');
            return
        }
        e.find('.weui-loading').remove();
        switch(e.attr(key)){

            case "1":
            if(typeof(v) == 'object') v = JSON.stringify(v);
            e.html(v);
            break;

            case "f":
            var vv = ((v/100).toFixed(2) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
            if( isNaN(v/100) ){vv = '0.00';}
            e.html(vv);
            break;

            case "int":
            var vv = (parseInt(v) + '').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
            if(isNaN(parseInt(v))){ vv = '0';}
            e.html(vv);
            break;

            case "i":
            if(!e.children('img').length){
                e.append("<img />");
            }
            var img = e.children('img')
            img.attr({src:v})
            img.siblings().remove()
            img.show();
            break;
            case "t":
            var vv = (!isNaN(v))?this.timestampFormat(v):v;
            e.html(vv)
            break;
            case "d":
            if(v && v!="0"){
                e.removeClass('hidden');
            }else{
                e.addClass('hidden');
            }
            break;

            case "none":
            if(v && v != "0"){
                e.addClass('hidden');
            }else{
                e.removeClass('hidden');
            }
            break;

            case "r":
            e.children().hide();
            e.children().first().siblings().remove();
            if(e.find("[range='body']").length) e = e.find("[range='body']");
            if(!v) return;
            if(typeof(v) != "object") v = eval("("+v+")");
            var tmp = e.find("[range='template']");
            if(tmp.length){
                var template_html = tmp.prop('outerHTML');
                tmp.remove();
            }else{
                var template_html = e.children().first().prop('outerHTML');
                e.html(template_html);
                e.children().first().hide();
            }
            for(var kk in v){
                var vv = v[kk];
                var line_html = template_html
                for(var kkk in vv){
                    var vvv = vv[kkk];
                    line_html = line_html.replace(eval("/__"+kkk+"__/g"),vvv)
                }
                e.append(line_html);
                var newline = e.children().last();
                newline.find('[range]').each(function(iii, eee) {
                    var kkk = $(eee).attr('name') || $(eee).get(0).tagName.toLowerCase();
                    VALUE.write($(eee),'range',vv[kkk]);
                });
                newline.show();
            }
            break;
        }
        e.fadeIn();
        e.trigger('bc-value-write')
    },
    timestampFormat:function ( timestamp ) {
        function zeroize( num ) {
            return (String(num).length == 1 ? '0' : '') + num;
        }

        var curTimestamp = parseInt(new Date().getTime() / 1000);
        var timestampDiff = curTimestamp - timestamp;

        var curDate = new Date( curTimestamp * 1000 );
        var tmDate = new Date( timestamp * 1000 );

        var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
        var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();

        if ( timestampDiff < 0 ) {
            var newDate = new Date( (curTimestamp + 86400) * 1000 );
            if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
                return '明天' + zeroize(H) + ':' + zeroize(i);
            } else if ( curDate.getFullYear() == Y ) {
                return  zeroize(m) + '-' + zeroize(d);
            } else {
                return  Y + '-' + zeroize(m) + '-' + zeroize(d);
            }
        } else if ( timestampDiff < 60 ) {
            return "刚刚";
        } else if( timestampDiff < 3600 ) {
            return Math.floor( timestampDiff / 60 ) + "分钟前";
        } else if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) {
            return '今天' + zeroize(H) + ':' + zeroize(i);
        } else {
            var newDate = new Date( (curTimestamp - 86400) * 1000 );
            if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
                return '昨天' + zeroize(H) + ':' + zeroize(i);
            } else if ( curDate.getFullYear() == Y ) {
                return  zeroize(m) + '-' + zeroize(d);
            } else {
                return  Y + '-' + zeroize(m) + '-' + zeroize(d);
            }
        }
    }
};
TIMER = {
    expiring:function(t){
        var t = $(t);
        var tm = t.find("timer");
        var res = tm.length > 0;
        return res;
    },
    complete:function(t){
        t.find("timer").remove();
        t.removeClass('weui-btn_disabled');
    },
    expire:function(t){
        var t = $(t);
        var tm = t.find("timer");
        if(!tm.length) return;
        var n = parseInt(tm.children().html());
        if(n>0){
            var tt = (n-1)?1000:150
            tm.children().html(n-1);
            setTimeout(function(){
                TIMER.expire(t);
            },tt);
        }else{
            this.complete(t);
        }
    },
    start:function(t,expirdIn){
        if(isNaN(parseInt(expirdIn))) return;
        var t = $(t);
        var tm = t.find("timer");
        if(!tm.length){
            t.append('<timer>(<t>'+expirdIn+'</t>)</timer>');
            tm = t.find("timer");
            setTimeout(function(){
                TIMER.expire(t);
            },1000);
        }else{
            tm.children().html(expirdIn);
        }
        if(t.hasClass('weui-btn') || t.hasClass('weui-vcode-btn')){
            t.addClass('weui-btn_disabled');
        }
    }
};
TOAST = {
    template:'<div class="toast" style="display:none;"><div class="weui-mask_transparent"></div><div class="weui-toast" style="z-index: 999999"><i class="weui-icon weui-icon-success-no-circle weui-icon weui-icon_toast"></i><i class="weui-loading weui-icon weui-icon_toast"></i><p class="weui-toast__content"></p></div></div>',
    load:function(html,fullhtml,maxTime){
        var tt = $(".toast");
        if( !tt || !tt.length ){
            $("body").append(this.template);
            tt = $(".toast");
        }
        $('body').css('overflow','hidden')
        tt.fadeIn(100,function(){
            tt.removeAttr('style');
        });
        var icon = tt.find("i.weui-loading");
        var content = tt.find(".weui-toast__content");
        icon.removeAttr('style');
        icon.siblings('i').hide();
        if(fullhtml){
            content.html(html);
        }else{
            content.html((langIsZh?"正在":"")+html);
        }
        if(maxTime){
            setTimeout(function(){
                tt.fadeOut(300,function(){
                    $('body').removeAttr('style');
                });
            },maxTime*1000);
        }
        $('input,textarea').blur();
    },
    error:function(){
        var tt = $(".toast");
        tt.fadeOut(300,function(){
        });
        $('body').removeAttr('style');
    },
    stop:function(){
        var tt = $(".toast").fadeToggle().remove();
        $('body').removeAttr('style');
    },
    success:function(html,fullhtml,time){
        var tt = $(".toast");
        if( !tt || !tt.length ){
            $("body").append(this.template);
            tt = $(".toast");
        }
        var icon = tt.find("i.weui-icon-success-no-circle")
        var content = tt.find(".weui-toast__content");
        icon.removeAttr('style');
        icon.siblings('i').hide();
        if(fullhtml){
            content.html(html);
        }else{
            content.html(html+(langIsZh?"成功":" success"));
        }
        if( tt.css('display') == "none" ){
            tt.fadeIn(100,function(){
                tt.removeAttr('style');
            });
        }
        setTimeout(function(){
            tt.fadeOut(300,function(){
            });
        },time*1000 || 500);
        $('body').removeAttr('style');
    },
    wran:function(html,fullhtml,time){
        var template = '<div class="toast" style="display:none;"><div class="weui-toast" style="z-index: 999999"><i class="weui-icon weui-icon-warn weui-icon_msg weui-icon weui-icon_toast"></i><i class="weui-loading weui-icon weui-icon_toast"></i><p class="weui-toast__content"></p></div></div>';
        var tt = $(".toast");
        if( !tt || !tt.length ){
            $("body").append(template);
            tt = $(".toast");
        }
        var icon = tt.find("i.weui-icon-warn")
        var content = tt.find(".weui-toast__content");
        icon.removeAttr('style');
        icon.siblings('i').hide();
        if(fullhtml){
            content.html(html);
        }else{
            content.html(html+(langIsZh?"失败":" wran"));
        }
        if( tt.css('display') == "none" ){
            tt.fadeIn(100,function(){
                tt.removeAttr('style');
            });
        }
        setTimeout(function(){
            tt.fadeOut(300,function(){
            });
        },time*1000 || 500);
        $('body').removeAttr('style');
    }
};
POST = {
    animate:{
        start:function(p){
            var $e = p.e
            console.log(" ---- BC-POST ("+(p.index)+") TRIGGER ---- ",$e,"bc.post.start")
            if($e.length) $e.trigger("bc-post-start");
            switch(p.style){

                case 0:
                TOAST.load(p.text);
                break;

                case 1:
                $e.blur();
                $e.prop('disabled',true);
                $e.parents('.weui-cell').removeClass('weui-cell_warn');
                if($e.hasClass('weui-switch')){
                    $e.fadeOut(1000,function(){
                        if($e.hasClass('bc-posting')){
                            $e.after("<span class='weui-loading'></span>")
                        }else{
                            $e.fadeIn();
                        }
                    })
                }else{
                    $e.hide();
                    $e.after("<span class='weui-loading'></span>")
                }
                case -1:
                return;
                break;
            }
        },
        clean:function(p,isError){
            var $e = p.e
            $e.next('.weui-loading').remove();
            $e.prop('disabled',false);
            if(isError){
                $e.parents('.weui-cell').addClass('weui-cell_warn');
                $e.fadeIn();
                if($e.hasClass('weui-switch')){
                    $e.prop("checked",!$e.prop('checked'))
                    return;
                }
            }else{
                if($e.hasClass('weui-switch')){
                    $e.fadeToggle();
                    $e.fadeIn();
                    return;
                }
                $e.next('.weui-icon').remove();
                $e.after("<span style='position: absolute;margin-left: -20px;' class='weui-icon weui-icon-original weui-icon-success'></span>")
                $e.show();
                var s = $e.next('.weui-icon');
                s.fadeOut('slow')
                // s.fadeOut('fast', function() {
                    // s.remove();
                    // $e.fadeIn();
                // });
            }

        },
        success:function(p){
            $e = p.e
            console.log(" ---- BC-POST ("+p.index+") TRIGGER [START] ---- ",$e)
            $e.trigger("bc-post-success");
            if($e.hasClass('weui-btn_disabled')) $e.removeClass('weui-btn_disabled');
            $e.removeClass('bc-posting');
            switch(p.style){
                case 0:
                TOAST.success(p.text);
                break;
                case 1:
                this.clean(p);
                case -1:
                return;
                break;
            }
        },
        error:function(p){
            $e = p.e
            $e.removeClass('bc-posting');
            if($e && $e.length){
                console.log(" ---- BC-POST ("+p.index+") TRIGGER [ERROR] ---- "+p.errormsg,$e)
                $e.trigger("bc-post-error",p.errormsg);
                var index = $e.attr("data-index") || 0;
                if($e.hasClass('weui-btn_disabled')) $e.removeClass('weui-btn_disabled');
                switch(p.style){
                    case 0:
                    TOAST.error();
                    break
                    case 1:
                    this.clean(p,true);
                    break;
                    case -1:
                    return;
                    break;
                    default:
                }
            }
            ERROR.top(p.text,p.errormsg);
        }
    },
    styles:{0:0,input:1,none:-1},
    init:function(e,c,target){
        var $e = $(e);
        if($e.hasClass('bc-post')) return;
        $e.addClass('bc-post');
        var method = c.method || 'click';
        var style = c.style || 0;
        var style = this.styles[style];
        var text = c.text || "处理"
        var msg = c.msg || {};
        $e.each(function(index, el) {
            var $e = $(el);
            $e.on(method,target,function(event,res){
                $e = $(this);
                if(c.stop && c.stop($e,event,res)){
                    event.preventDefault();
                    $e.removeClass('bc-posting');
                    return;
                }
                if(c.confirm){
                    if(typeof(c.confirm) == 'function'){
                        var data_confirm = c.confirm(this,event)
                        var str = data_confirm.text || text;
                        str = "确认"+str;
                        if(data_confirm.target) str += " ["+ data_confirm.target +"] ";
                    }else{
                        str = "确认"+text;
                    }
                    if(!confirm(str+"?")){
                        if(c.cancel) c.cancel($e);
                        return;
                    }
                }
                if($e.hasClass('bc-posting')||$e.hasClass('weui-btn_disabled')) return;
                if($e.hasClass('weui-btn') || $e.hasClass('weui-vcode-btn')) $e.addClass('weui-btn_disabled');
                $e.addClass('bc-posting');
                var index = parseInt( $e.attr("data-index") || 0 );
                var title = $e.parents(".weui-cells").prev(".weui-cells__title").children("label").first();
                if(title && title.length){
                    var index = parseInt( title.attr("data-index") || 0 );
                }
                var url = c.url || '/test/getlist';
                if(url== "/test/getlist"){
                    console.error($e,"test-port");
                }
                if(c.input || false){
                    var data = c.input(this,event,res);
                }else{
                    var data = {}
                    var name = $(this).attr("name");
                    if(name){
                        data['key'] = name;
                        switch($(this).attr("type")){
                            case "radio":
                            if($(this).prop("checked")) data['value'] = $(this).val();
                            break;
                            case "checkbox":
                            data['value'] = $(this).prop("checked");
                            break;
                            default:
                            data['value'] = $(this).val();
                            break;
                        }
                    }

                }
                var ld = c.loading?$(c.loading(this)):{};
                if(ld.length){
                    var weui_ld = ld.find('.weui-loading');
                    if(!weui_ld.length){
                        ld.append('<i class="weui-loading"></i>');
                        weui_ld = ld.children().last();
                    }
                    weui_ld.fadeIn();
                };
                POST.animate.start({e:$e,style:style,text:text,index:index});
                console.log(" ---- BC-POST ("+index+") ---- ",url,data)
                var element = $e;
                $.ajax({
                    type:"post",
                    url:url,
                    data:data,
                    xhrFields:{
                        withCredentials:true
                    },
                    success:function(ret){
                        if(ld.length){
                            var weui_ld = ld.find('.weui-loading');
                            weui_ld.fadeOut();
                        }
                        console.log(" ---- BC-POST ("+index+") RETURN ---- ",ret)
                        ret = ret || {}
                        if(!ret || !ret.state ){
                            var errormsg = ret.errormsg
                            if(langIsZh){
                                var errormsg_text = msg[errormsg] || errormsg;
                            }else{
                                var errormsg_text = errormsg
                            }
                            POST.animate.error({e:$e,style:style,text:text,errormsg:errormsg_text,index:index});
                            if(c.error) c.error(element,ret);
                            return
                        }
                        POST.animate.success({e:$e,style:style,text:text,index:index});
                        if(c.success) c.success(element,ret);
                    },
                    error:function(xhr){
                        var errormsg = xhr.statusText + " " + xhr.status ;
                        $e.removeClass('bc-posting');
                        POST.animate.error({e:$e,style:style,text:text,errormsg:errormsg,index:index});
                        if(c.error) c.error(element,{errormsg:errormsg});
                    }
                })
            })
        })
    }
};
DETAIL = {
    content:{},
    init:function(){
        $(document).on('bc-page-success bc-view-success', function(event) {
            var e = $(event.target);
            e.find(".bc-detail,.bc-list-detail").not(".no-init").each(function(index, el) {
                DETAIL.put(el);
            });
        });
        // var d = $(t).find(".bc-list-detail,.bc-detail");
        // this.put(d);
    },
    put:function(d,content){
        var d = $(d).closest('.bc-list-detail,.bc-detail');
        if(!d || !d.length){
            return false;
        }
        d.find(".bc-post-error,.bc-post-success").remove();
        d.find(".weui-cell_warn").removeClass('weui-cell_warn');
        var content = content || DETAIL.content;
        if(!content || ! (content.length || Object.keys(content).length)){
            return
        }
        d.find("[detail]").each(function(index, el) {
            var e = $(el);
            var key = e[0].tagName.toLowerCase();
            if(key=="input" || key=="textarea" || key=="select"){
                key = $(el).attr("name");
            }
            // console.log(!content,content.length);
            if(!content){
                var v = "";
            }else if(eval("content."+key)){
                var v = content[key];
            }else{
                var v = $(content).find(key).html();
            }
            VALUE.write(e,"detail",v)
            // console.log(" ---- BC-DETAIL TRIGGER ---- ",e,"bc.detail.success")
            DETAIL.contnent = {};
        });
        d.trigger("bc-detail-success");
    },
    clean:function(t){
        var d = $(t).closest(".bc-list-detail,.bc-detail");
        if(!d || !d.length){
            return false;
        }
        DETAIL.content = $();
        DETAIL.put(d);
    }
};
URLS = {
    hash:function(){
        var url = location.hash.indexOf('#') === 0 ? location.hash.replace("#","").split("/")[0] : "home" ;
        return url;
    },
    ids:function(){
        var u = location.hash.indexOf('#') === 0 ? location.hash.split("/") : [] ;
        var url = [];
        for( var i in u){
            if(i>0) url[url.length] = u[i];
        }
        return url
    }
};
INFO = {
    cache:{},
    $info:null,
    page:null,
    errorhtml:'<div class="weui-msg bc-info-error"><div class="weui-msg__icon-area"><i class="weui-icon weui-icon-warn weui-icon weui-icon_msg"></i></div><div class="weui-msg__text-area"><h2 class="weui-msg__title">内容无法获取</h2><p class="weui-msg__desc"><reason></reason></p></div></div>',
    errorhtmlSimple:'<span class="weui-icon weui-icon-warn weui-icon-original">?<span>',
    loadinghtml:'<div class="weui-msg bc-info-loading"><div class="weui-msg__icon-area"><i class="weui-icon weui-icon-waiting weui-icon weui-icon_msg"></i></div><div class="weui-msg__text-area"><h2 class="weui-msg__title"><i class="weui-loading"></i>加载中</h2><p class="weui-msg__desc"><reason></reason></p></div></div>',
    loadinghtmlSimple:"<i class='weui-loading'></i>",
    init:function(){
        $(".bc-list-info,.bc-info").not(".no-init").each(function(index, el) {
            INFO.reload(el);
        });
        $(document).on('bc-page-success bc-view-success', function(event) {
            var e = $(event.target);
            e.find(".bc-list-info,.bc-info").not(".no-init").each(function(index, el) {
                INFO.reload(el);
            });
        });
        $(document).on('click', '.bc-info-click-reload,.bc-info-reload', function(event) {
            var e = $(event.target);
            INFO.reload(e);
            event.preventDefault();
        });
    },
    error:function(t,index,reason){
        t.find("error").fadeIn();
        t.find("display").hide();
        if(!t.trigger) return;
        t.find("[info]").each(function(i, el) {
            var e = $(el)
            VALUE.write(e,"info",null);
        });
        console.log(" ---- BC-INFO ("+index+") TRIGGER ---- ",t,"info-error",reason);
        t.trigger("bc-info-error",reason)
        switch(t.attr('data-error')){
            case 'post':
            POST.animate.error({errormsg:reason});
            return;
            break;
        }
        if(!t.hasClass('bc-list-info') && t.find("[info]").length == 0){
            t.html(this.errorhtmlSimple.replace("?",reason)); return;
        }
        if(t.hasClass('bc-info')) return;
        t.hide();
        t.after(this.errorhtml).next().find('reason').html(reason);
    },
    input:function(){
        var t = this.$info;
        // if(!this.page){
            // this.error("page error");
            // return false;
        // }
        var keys = (t.attr('data-keys') || "").split(",");
        var ids = URLS.ids();
        if(ids.length == 0) return null;
        data = {};
        for(var i in ids){
            var d = ids[i];
            if(!d) continue;
            if(!keys[i] && i>0 ) break;
            var k = keys[i]?keys[i]:"id";
            data[k] = ids[i];
        }
        return data;
    },
    put:function(t,$info){
        var t = $(t);
        if(!t.length) return;
        t.find("error").hide();
        t.find("display").fadeIn();
        this.$info = t = $(t).closest('.bc-info,.bc-list-info');
        t.find("[info]").each(function(index0, el) {
            var e = $(el);
            var key = e[0].tagName.toLowerCase();
            if(key=="input" || key=="textarea" || key=="select"){
                key = $(el).attr("name");
            }
            var v = $info[key];
            VALUE.write(e,"info",v)
            t.trigger("bc-info-put-data")
        });
        var index = t.attr("data-index");
        console.log(" ---- BC-INFO ("+index+") TRIGGER ---- ",t,"success",t.find("[info]"))
        t.trigger("bc-info-success",$info);
        // if(showLoading)
        if(t.css("display")=='none') t.fadeToggle().fadeIn(501);
    },
    reload:function(t, data, nocache){
        $(t).each(function(index, el) {
            INFO._reload(el,data,nocache);
        });
    },
    _reload:function(t, data,nocache){
        this.$info = t = $(t).closest('.bc-info,.bc-list-info');
        if(!t || !t.length) return;
        var showLoading = !t.hasClass("bc-info")
        var simple = t.find("[info]").length?false:true;
        if(simple){
            t.html(this.loadinghtmlSimple);
        }
        t.next(".bc-info-error").remove();
        if(showLoading) t.hide();
        var cache = t.attr("cache");
        if(!nocache && cache){
            // try{eval(cache)}catch(e){eval(cache+"={}")}
            // console.log(user);
            var info_cache = eval("INFO.cache."+cache);
            if( info_cache ){
                this.put(t,info_cache);
                return
            }
        }
        // console.log(t);
        var port_value = t.attr("data-port-value");
        if(port_value){try{port_value = eval(port_value);}catch(e){port_value=null};}
        var port = port_value || t.attr("data-port") || "/test/info";
        if(port == '/test/info'){
            console.error(t,"test-port");
        }
        if(!port){
            this.error("port error")
            return
        }
        if(!data) data = this.input();
        if(t.hasClass('.bc-list-info') && data === false){
            return
        }
        if(showLoading) t.after(this.loadinghtml)
            var index = parseInt( t.attr("data-index") || 0 ) + 1;
        t.attr("data-index",index);
        console.log(" ---- BC-INFO ("+index+") ---- ",port,data)
        console.log(" ---- BC-INFO ("+index+") TRIGGER ---- ",t,"start")
        t.trigger("bc-info-start");
        if(t.find('.bc-info-loading-full').length){t.find('.bc-info-loading-full').show();t.find('.bc-info-loading-full').siblings().hide();}else{VALUE.loading(t,"info")}
        $.ajax({
            url: port,
            data: data,
            xhrFields:{
                withCredentials:true
            },
            // dataType: 'json',
            success:function(ret){
                if(t.find('.bc-info-loading-full').length){t.find('.bc-info-loading-full').hide();t.find('.bc-info-loading-full').siblings().show();}
                var index2 = parseInt( t.attr("data-index") || 0 ) ;
                if( index2 != index ) return;
                console.log(" ---- BC-INFO ("+index+") RETURN ---- ",typeof(ret),ret)
                t.next(".bc-info-loading").remove();
                if(typeof(ret) == 'string'){
                    t.html('');
                    t.html(ret);
                    t.fadeIn();
                    return
                }
                if(!ret.state){
                    INFO.error(t,index,ret.errormsg);
                    return
                }
                var $info = ret.data?ret.data.info:null ;
                if(!$info){
                    INFO.error(t,index,"info missing");
                    return
                }
                if(simple){
                    var key = t.attr('info');
                    var v = ret.data.info[key];
                    // console.log(ret,key)
                    t.html(v);
                    console.log(" ---- BC-INFO ("+index+") TRIGGER ---- ",t,"info-success",v)
                    t.trigger("bc-info-success",v);
                    return
                }
                if(cache){
                    eval("INFO.cache."+cache+" = $info");
                }
                INFO.put(t,$info)
            },
            error:function(xhr, type){
                if(t.find('.bc-info-loading-full').length){t.find('.bc-info-loading-full').hide();t.find('.bc-info-loading-full').siblings().show();}
                var index2 = parseInt( t.attr("data-index") || 0 ) ;
                if( index2 != index ) return;
                t.next(".bc-info-loading").remove();
                INFO.error(t,index,xhr.statusText + " " + xhr.status )
            }
        })
    }
};
LIST = {
    $list:{
        loadTemplate:{
            error   : "<div class='bc-list-loadmore error weui-loadmore weui-loadmore_line' onclick='LIST.reload(this)' ><span class='weui-loadmore__tips' style=color:maroon>code</span></div>",
            loading : "<div class='bc-list-loadmore loading weui-loadmore'><i class='weui-loading'></i><span class='weui-loadmore__tips'>正在加载</span></div>",
            empty   : "<div class='bc-list-loadmore empty weui-loadmore weui-loadmore_line'><span class='weui-loadmore__tips'>暂无内容</span></div>",
            nomore  : "<div class='bc-list-loadmore nomore weui-loadmore weui-loadmore_line weui-loadmore_dot'><span class='weui-loadmore__tips'></span></div>",
            loadmore: "<div class='bc-list-loadmore loadmore weui-panel__ft' onclick='LIST.loadmore(this)' align='center' ><a href='javascript:void(0);' class='weui-cell weui-cell_access weui-cell_link'><div class='weui-cell__bd' style='padding:8px;'>加载更多</div></a></div>"
        }
    },
    init:function(){
        $(document).on('change','.bc-list', function(event) {
            var e = $(event.target);
            if(e.closest('.bc-list-template,.bc-list-content,.bc-btn-group').length){
                return true;
            }
            LIST.reload(e);
        });
        $(document).on('bc-page-success bc-view-success', function(event) {
            var e = $(event.target);
            e.find(".bc-list").not(".no-init").each(function(index, el) {
                LIST.reload(el);
            });
        });
        $(document).on('bc-detail-success', function(event) {
            var e = $(event.target);
            e.find(".bc-list").each(function(index, el) {
                LIST.reload(el);
            });
        });
        this.pageInit();
    },
    pageInit:function(){
        // if(!this.find(t)){
            // return false;
        // }
        var l = this.$list;
        $(document).on('click',".bc-list-edit", function(event) {
            LIST.closest(this)
            var t = $(this)
            var l = LIST.$list;
            // console.log(l,t)
            if(t.hasClass('active')){
                t.text("编辑")
                t.removeClass('active')
                l.checkbox.hide();
                l.menu.hide();
                l.menu.siblings().not('.bc-list-edit').fadeIn();
                l.link.fadeIn(1100);
                l.content.children().removeClass('editing');
                l.content.find(".weui-cell__ft,.bc-list-edit-hide").fadeIn();
            }else{
                t.text("完成")
                t.addClass('active')
                l.checkbox.find("input[type='checkbox']").prop('checked',false);
                l.checkbox.fadeIn();
                l.menu.fadeIn(1100);
                l.menu.siblings().not('.bc-list-edit').hide();
                l.link.hide();
                l.content.children().addClass('editing');
                l.content.find(".weui-cell__ft,.bc-list-edit-hide").hide();
            }
        });
        $(document).on('click',".bc-list-reload", function(event) {
            var target = $(this).attr('data-target');
            if(target){
                LIST.reload(target);
            }else{
                LIST.reload(this);
            }
        })
        $(document).on('click',".bc-list-selectAll", function(event) {
            LIST.selectAll(this);
        });
        $(document).on('click',".bc-list-selectReverse", function(event) {
            LIST.selectReverse(this);
        });
    },
    selectAll:function(t){
        if(t) this.closest(t);
        this.$list.checkbox.find("input[type='checkbox']").prop("checked",true);
    },
    selectReverse:function(t){
        if(t) this.closest(t);
        this.$list.checkbox.find("input[type='checkbox']").each(function(i,n){
            $(n).prop('checked',!$(n).is(":checked"));
        })
    },
    selected:function(t){
        if(t) this.closest(t);
        var ids = []
        this.$list.checkbox.find("input:checked").each(function(index, el) {
            var new_id = $(el).closest('[data-id]').attr('data-id');
            if(new_id) ids.push(new_id);
        });
        return ids;
    },
    ids:function(t){
        if(t) this.closest(t);
        var ids = []
        this.$list.content.children().each(function(index, el) {
            var id = $(el).attr("data-id");
            if(id) ids.push(id);
        });
        return ids;
    },
    input:function(t){
        if(t) this.closest(t);
        var input = {};
        var l = this.$list;
        l.bar.find("input,textarea,select").not(".bc-list-template *,.bc-btn-group *").each(function(index, el) {
            e = $(el)
            switch(e.prop('type')){
                case "radio":
                if(e.prop('checked')){
                    input[e.prop('name')] = e.val()
                }
                break;
                case "checkbox":
                if(e.prop('checked')){
                    input[e.prop('name')] = true;
                }
                break;
                default:
                if(e.prop('name') && e.val().length){
                    input[e.prop('name')] = e.val()
                }
                break;
            }
        });
        // input['page'] = parseInt(l.page)+1;
        // console.log(input)
        return input;
    },
    reload:function(t,data){
        $(t).each(function(index, el) {
            LIST._reload(el,data);
        });
    },
    _reload:function(t,data){
        if(t) this.closest(t);
        if(!this.$list.template){
            console.error('list need template',t)
            return;
        }
        var l = this.$list
        l.edit.text("编辑");
        l.edit.removeClass('active')
        l.checkbox.hide();
        l.menu.hide();
        l.menu.siblings().not('.bc-list-edit').show();
        l.link.fadeIn(1100);
        l.content.children().removeClass('editing');
        l.content.find(".weui-cell__ft,.bc-list-edit-hide").show();
        // l.menu.hide();
        // l.edit.text("编辑");
        // l.edit.removeClass('active')
        // l.menu.siblings().not('.bc-list-edit').show();
        // l.checkbox.hide();
        this.$list.loadmore.remove();
        // console.log($(t),this.$list)
        if(this.$list.content && this.$list.content.length){
            if(this.$list.content.height()>23){
                this.$list.content.css({height:this.$list.content.height()});
            }
            this.$list.content.html("");
            if(!this.$list.nomore){
                this.$list.content.append(this.$list.loadTemplate.loading)
            }
        }else{
            // console.log(this.$list.template);
            if(!this.$list.nomore){
                // console.log(this.$list)
                this.$list.template.after(this.$list.loadTemplate.loading)
            }
        }
        this.$list.bar.removeAttr('page');
        this.$list.page = 0;
        this.ajax(t,data);
    },
    loadmore:function(t){
        if(t) this.closest(t);
        if(!this.$list.nomore){
            this.$list.loadmore.remove();
            this.$list.content.after(this.$list.loadTemplate.loading)
        }
        var l = this.$list
        l.edit.text("编辑");
        l.edit.removeClass('active')
        l.checkbox.hide();
        l.menu.hide();
        l.menu.siblings().not('.bc-list-edit').fadeIn();
        l.link.fadeIn(1100);
        l.content.children().removeClass('editing');
        l.content.find(".weui-cell__ft,.bc-list-edit-hide").show();
        this.ajax();
    },
    ajax:function(t,data){
        var tt = this
        var l = this.$list
        // console.log(l)
        // return;
        var bar = l.bar
        if(!data) var data = this.input();
        var dataId = this.$list.dataId;
        var url = l.port;
        var content = l.content
        var template = l.template.eq(0)
        var template_html = l.t
        var portIndex = parseInt(l.portIndex)+1;
        if(!l.content || !l.content.length){
            template_class = template.prop("class").replace("bc-list-template","");
            template_tag = template.prop("tagName");
            content_html = "<"+template_tag+" class='"+template_class+" bc-list-content'></"+template_tag+">";
            template.before(content_html)
            tt.$list.content = l.content = content = bar.find(".bc-list-content")
        }
        if(bar.find('.bc-list-header').length && !content.prev('.bc-list-content-header').length){
            content.before(template_html);
            var hd = content.prev();
            hd.removeClass('bc-list-header');
            hd.removeClass('weui-cell_access');
            hd.addClass('bc-list-content-header');
            hd.find('hd').siblings().remove();
        }
        bar.attr({'data-port-index':portIndex});
        template.hide();
        console.log(" ---- BC-LIST ("+portIndex+") ---- ",url,data)
        console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",bar,"start")
        bar.trigger("bc-list-start")
        $.ajax({
            url: url,
            data: data,
            xhrFields:{
                withCredentials:true
            },
            success: function(ret){
                console.log(" ---- BC-LIST ("+portIndex+") RETURN---- ",ret)
                if( parseInt(bar.attr('data-port-index')) != portIndex ){
                    return
                }
                bar.find('.bc-list-loadmore').remove();
                if(!ret.state){
                    var errormsg = ret.errormsg + " " + (bar,ret.errorcode||"");
                    LIST.error(bar,errormsg);
                    console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",bar,"error",errormsg)
                    bar.trigger("bc-list-error",errormsg)
                    return
                }
                var c = ret.data.list;
                LIST.page = ret.page;
                if(!c){
                    content.after(l.loadTemplate.empty);
                    content.removeAttr('style')
                    return false;
                }
                bar.attr('data-page',parseInt(l.page)+1)
                var length = parseInt(content.children().length);
                var n = 0;
                for( i in c ){
                    var d = c[i];
                    if(dataId){
                        exist = content.children("[data-id='"+d[dataId]+"']")
                        if(exist && exist.length){
                            continue;
                        }
                    }
                    content.append(template_html);
                    line = content.children().eq(length+parseInt(n))
                    // console.log('d[dataId]',d[dataId])
                    line.attr({'data-id':d[dataId]})
                    line.addClass('bc-list-new').hide();
                    line.find('hd').remove();
                    line.addClass('bc-list-line');
                    line.find("[list]").each(function(index, el) {
                        var e = $(el);
                        var k = e.get(0).tagName.toLowerCase();
                        if(k == 'input') k = e.attr('name');
                        var v = d[k];
                        VALUE.write(e,"list",v)
                        // console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",e,"value")
                        e.trigger("bc-list-put-value")
                    });
                    var detailBox = line.append('<div class="bc-list-detail-box bc-modal-data"></div>').find(".bc-list-detail-box").hide();
                    for(var k in d ){
                        var v = d[k];
                        if(typeof(v) == "object"){
                            // v = jQuery.parseJSON(v);
                            v = JSON.stringify(v);
                        }
                        if(v == null || v == 'null') v = "";
                        // if(d[k])
                        detailBox.append("<"+k+" list=1>"+v+"</"+k+">");
                    }
                    n++;
                    // console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",line,"line")
                    line.trigger("bc-list-new-line")
                }
                if(l.edit.length){
                    content.children(".bc-list-new").on('click', function(event) {
                        DETAIL.content = $(this).find(".bc-list-detail-box");
                        // console.log('put',detail.content)
                        if($(this).hasClass('editing')){
                            box = $(this).find(".bc-list-checkbox input");
                            box.prop("checked",!box.prop('checked'))
                            event.preventDefault();
                        }else{
                            var href = $(this).attr('href');
                            if(href){
                                if(href && href.indexOf("javascript")>=0){
                                    eval(href);
                                }else{
                                    location.href = href
                                }
                                event.preventDefault();
                            }else{
                            }
                        }
                    });
                    content.find(".bc-list-checkbox").hide();
                    // l.edit.text("编辑");
                    // l.edit.removeClass('active')
                    // l.checkbox.hide();
                    // l.menu.hide();
                    // l.menu.siblings().not('.bc-list-edit').show();
                }
                content.children(".bc-list-new").removeClass('bc-list-new').fadeIn(1000);
                content.removeAttr('style');
                if(!l.nomore){
                    if(ret.data.more){
                        content.after(l.loadTemplate.loadmore);
                    }else{
                        content.after(l.loadTemplate.nomore);
                    }
                }
                console.log(" ---- BC-LIST ("+portIndex+") TRIGGER ---- ",bar,"success")
                bar.trigger("bc-list-success")
            },
            error: function(xhr, type){
                LIST.error(bar,xhr.statusText+" "+xhr.status);
            }
        })
},
error:function(bar,msg){
    var content = bar.find('.bc-list-content')
    content.removeAttr('style')
    bar.find('.bc-list-loadmore').remove();
    if(content && content.length){
        var a = content
    }else{
        var a = bar.find(".bc-list-template")
    }
    a.after(LIST.$list.loadTemplate.error.replace('code',msg));
},
detail:function(t){

},
find:function(t){
    t = $(t).find('.bc-list')
    if(!t.length){
        return false;
    }
    return this.$(t);
},
closest:function(t){
    t = $(t).closest('.bc-list')
    if(!t.length){
        return false;
    }
    return this.$(t);
},
$:function(t){
    this.$list = {loadTemplate:this.$list.loadTemplate}
    this.$list.bar = t;
    if(!t){
        return false;
    }
    this.$list.portIndex         = t.attr("data-port-index") || parseInt(100*Math.random())*1000;
    var port_value = t.attr("data-port-value");
    if(port_value){try{port_value = eval(port_value);}catch(e){port_value=null};}
    this.$list.port              = port_value || t.attr("data-port") || "/test/getlist";
    if(this.$list.port == "/test/getlist"){
        console.error(t,"test-port");
    }
    this.$list.page              = t.attr("data-page") || 0;
    this.$list.dataId            = t.attr("data-id") || "id";
    this.$list.template          = t.find(".bc-list-template");
    this.$list.t                 = t.find(".bc-list-template").html();
    this.$list.content           = t.find(".bc-list-content");
    this.$list.loadmore          = t.find(".bc-list-loadmore");
        // this.$list.selectAll         = t.find(".bc-list-select-all");
        // this.$list.selectReverse     = t.find(".bc-list-select-reverse");
        this.$list.edit             = t.find(".bc-list-edit");
        this.$list.menu             = t.find(".bc-list-menu");
        this.$list.link             = t.find(".bc-list-link");
        this.$list.checkbox         = t.find(".bc-list-content .bc-list-checkbox");
        this.$list.nomore           = t.attr("nomore") || 0;
        return true;
    }
};
RANK = {
    $rank:null,
    init:function(){
        RANK.reload('.bc-rank');
        $(document).on('bc-page-success bc-view-success', function(event) {
            var e = $(event.target);
            e.find(".bc-rank").not(".no-init").each(function(index, el) {
                RANK.reload(el);
            });
        });
        $(document).on('click', '.bc-rank-reload', function(event) {
            RANK.reload(this);
        });
    },
    error:function(t,errormsg){
        var portIndex = 0;
        console.log(" ---- BC-RANK ("+portIndex+") TRIGGER ---- ","error",errormsg)
        t.trigger("bc-rank-error",errormsg)
        // post.animate.error({errormsg:errormsg})
    },
    put:function(t,res,rank_detail){
        var t = $(t).closest('.bc-rank');
        if(!t || !t.length) return;
        var template = t.find(".bc-rank-template");
        template.hide();
        t.find(".bc-rank-content").remove();
        // var res = ret.data.rank;
        var template_html = template.prop("outerHTML").replace(/bc-rank-template/g,"bc-rank-content").replace(/bc-img-template/g,"bc-img-content");
        for( var i in res){
            var v = res[i]
            var content_html = template_html;
            // console.error(typeof(v))
            switch(typeof(v)){
                case "string":
                content_html = content_html.replace(/__value__/g,v);
                template.parent().append(content_html);
                var newRank = template.parent().children().last();
                break;
                case "object":
                var c = content_html;
                for(var ii in v){
                    if(typeof(v[ii]) == 'string') c = c.replace(eval('/__'+ii+'__/g'),v[ii].trim());
                }
                content_html = c;
                template.parent().append(content_html);
                var newRank = template.parent().children().last();
                if(rank_detail){
                    newRank.append('<div class="hidden bc-rank-detail"></div>');
                    var newDetailBox = newRank.find('.bc-rank-detail');
                    for(var ii in v){
                        newDetailBox.append("<"+ii+" class='hidden'>"+v[ii]+"</"+ii+">");
                    }
                }
                newRank.find('[rank]').each(function(index, el) {
                    var e = $(el);
                    var k = e.get(0).tagName.toLowerCase();
                    if(k == 'input') k = e.attr('name')
                        var vv = v[k];
                    if(typeof(vv) == "object"){
                        // v = jQuery.parseJSON(v);
                        vv = JSON.stringify(vv);
                    }
                    if(vv == null || vv == 'null') vv = "";
                    VALUE.write(e,'rank',vv)
                });
                break;
                default:
                var newRank = null;
            }
            if(newRank) newRank.trigger('bc-rank-new');newRank.addClass('active');
            // template.parent().append(content_html);
            // var newrank = template.parent().children().last();

        }
        template.siblings('.bc-rank-content').fadeIn();
        console.log(" ---- BC-RANK ("+0+") TRIGGER ---- ",t,"bc-rank-success")
        t.trigger("bc-rank-success")
    },
    clean:function(t){
        var t = $(t).closest('.bc-rank');
        if(!t || !t.length) return;
        t.find(".bc-rank-content,.bc-rank-error").remove();
        var template = t.find(".bc-rank-template");
        if(!template.length){
            console.error('rank template error',t);
            return
        }
        t.find(".bc-rank-loading").fadeIn();
        template.hide();
    },
    reload:function(t,data){
        $(t).each(function(index, el) {
            RANK._reload(el,data);
        });
    },
    _reload:function(t,data){
        var t = $(t).closest('.bc-rank');
        if(!t || !t.length) return;
        //界面处理
        RANK.clean(t);
        if(t.hasClass('bc-rank-detail')){
            var rank_detail = true;
        }
        //接口访问
        var port_value = t.attr("data-port-value");
        if(port_value){try{port_value = eval(port_value);}catch(e){port_value=null};}
        var url = port_value || t.attr("data-port") || "/test/rank";
        if(url == '/test/rank'){
            console.error(t,"test-port");
        }
        var data = data || {};
        $.ajax({
            url: url,
            data:data,
            xhrFields:{
                withCredentials:true
            },
            success:function(ret){
                t.find(".bc-rank-content,.bc-rank-error").remove();
                t.find(".bc-rank-loading").hide();
                console.log(" ---- BC-RANK ("+0+") TRIGGER ---- ",t,"rank-start",ret,url)
                t.trigger("bc-rank-start");
                // console.error(ret);
                if(!ret){
                    RANK.error(t,'数据返还为空')
                    return
                }
                if(!ret.state){
                    var errormsg = ret.errormsg;
                    RANK.error(t,errormsg)
                    return
                }
                if(!ret.data || !ret.data.rank){
                    var errormsg = "rank missing";
                    RANK.error(t,errormsg)
                    return
                }
                RANK.put(t,ret.data.rank,rank_detail);
            },
            error:function(xhr){
                t.find(".bc-rank-loading").hide();
                var errormsg = xhr.statusText + " " + xhr.status
                RANK.error(t,errormsg);
            }
        });
    }
};
MODAL = {
    init:function(){
        $(document).on('click', '[data-toggle="modal"]:not(.weui-btn_disabled)', function(event) {
            var e = $(this)
            var k = $(this).attr('data-target');
            var dt = $(this).attr('data-detail');
            var m = $(k+".modal")
            var d = $(this).closest('.bc-modal-data')
            if(!d.length) d = $(this).find('.bc-modal-data')
                MODAL.open(m,d,e);
            if(dt) DETAIL.put($(k).find('.bc-detail'),$(dt));
            event.preventDefault();
        });
        $(document).on('bc-tab-success', function(event) {
            MODAL.resize($(event.target).closest('.modal'));
        });
        $(document).on('click', '[data-dismiss="modal"],[modal="close"]', function(event) {
            MODAL.close($(this).closest('.modal'));
            event.preventDefault();
        });
        $(document).on('click touchend', '.modal-backdrop', function(event) {
            MODAL.close($(this).closest('.modal'));
            event.preventDefault();
        });
        $(document).keydown( function(e){
            if(e.which == '27' ) MODAL.close(".modal");
        });
    },
    toggle:function(m){
        var m = $(m)
        if(!m || !m.length) return;
        m.fadeToggle().fadeOut(0,function(){
            $(".page__body").removeClass('no-blur');
            $('body').removeAttr('style');
        });
    },
    close:function(m){
        if(!m) m = '.modal';
        $(m).each(function(index, el) {
            MODAL._close(el);
        });
    },
    _close:function(m){
        var m = $(m)
        if(!m || !m.length) return;
        if(!m.hasClass('bc-modal-active')) return;
        m.trigger("bc-modal-close").removeClass('bc-modal-active');
        m.fadeToggle().fadeOut(100,function(){
            $(".page__body").removeClass('no-blur');
            $('body').removeAttr('style');
        });
    },
    resize:function(m){
        /**
         var m = $(m)
         var d = m.find(".modal-dialog");
         var h = d.height()
         var hh = $(window).height();
         var mg = ( hh - h - 100 ) / 2;
         if(mg<50) mg = 50;
         // console.log(h,hh,mg)
         d.css('margin-top',mg);
         */
        var m = $(m);
        var d = m.find('.modal-dialog');
        var h = d.height();
        var hh = $(window).height();
        var dHeight=m.offsetHeight;
        var dWidth=m.offsetWidth;
        var wHeight=document.documentElement.clientHeight;
        var sWidth=document.body.scrollWidth;
        var sHeight=document.body.scrollHeight;
        var left=sWidth/2-dWidth/2+"px";
        var top=wHeight/2-dHeight/2+"px";
        m.css({
            left: left,
            top: top
        });
    },
    open:function(m,data,element){
        var m = $(m)
        if(!m || !m.length) return;
        $(".modal").hide();
        if(data && data.length){
            m.find("[modal]").each(function(index, el) {
                var e = $(el)
                var kk = e.attr("name") || e[0].tagName.toLowerCase();
                var vv = data.find("[name='"+kk+"']").val() || data.find(kk).html() || "";
                VALUE.write(e,'modal',vv);
            });
        }
        m.trigger('bc-modal-start');
        var d = m.find(".modal-dialog");
        var backdrop = m.find(".modal-backdrop");
        if(!backdrop || !backdrop.length){
            m.prepend('<div class="modal-backdrop"></div>');
        }
        m.fadeToggle().fadeIn(100);
        $(".page__body").addClass('no-blur');
        this.resize(m);
        $('body').css('overflow','hidden')
        // console.log(element);
        m.trigger('bc-modal-success',element);
        m.addClass('bc-modal-active');
        m.find('.bc-modal-focus').focus();
    }
};
TAB = {
    init:function(){
        $(document).on('click touchend', '.bc-tab .bc-tab-menu>label', function(event) {
            TAB.select(this,true);
        });
        $(document).on('mouseenter', '.bc-tab .bc-tab-menu.bc-tab-menu-hover>label', function(event) {
            TAB.select(this,true);
        });
    },
    select:function(e,autoCheck){
        var self = $(e);
        if($(e).hasClass('bc-tab-active')){
            return;
        }
        var tab = self.parents('.bc-tab');
        var index = self.index()
        var content = tab.find(".bc-tab-content");
        self.addClass('bc-tab-active');
        self.trigger("bc-tab-activate");
        var old = self.siblings(".bc-tab-active")
        // console.log(self,'old',old)
        old.trigger("bc-tab-inactivate");
        old.removeClass('bc-tab-active');
        content.children().hide();
        var i = content.children().eq(index);
        i.fadeIn().trigger('bc-tab-success');
        if(!autoCheck){
            self.find('input').prop('checked',true);
            old.find('input').prop('checked',false);
        }
    }
};
PAGE = {
    container:$('#container'),
    default:"home",
    stack:[],
    url:null,
    exist:function(url){
        for( var i in this.stack ){
            if( this.stack[i].url == url ) return true;
        }
        return false
        return $("[page_id='"+url+"']").length > 0;
    },
    id:function(){
        var h = location.hash.replace("#","").split("/");
        if(h.length){
            return h[1];
        }
        return null;
    },
    getHtml:function(url){
        var r = $('script[type="text/html"]#tpl-'+url).html();
        if(r) return r.replace(/<sss>/g,"<script>").replace(/<\/sss>/g,"</script>");
        var p = document.location.toString().split(/\/\/|\#/);
        var p1 = p[1].split(/\/|\?/);p1=p1[1];
        var p2 = p.length>1?p[2]:'home';
        var res = "<div class='page page-remove'><div class='bc-view' data-port='/"+p1+"/"+p2+"'></div></div>";
        return res;
    },
    getId:function(){
        var h = location.hash.replace("#","")
        if(h){
            h = h.split("/")
            if(h.length>1){
                var e = [];
                for(var i in h){
                    if(i>0){
                        e.push(h[i]);
                    }
                }
                return e;
            }
        }
        return null;
    },
    getUrl:function(){
        var url = this.url
        if(url) return url
            var h = location.hash.replace("#","").split("/")
        if(!h.length){
            url = this.default;
        }else{
            url = h[0]
        }
        if(url == ""){
            url = this.default;
        }
        // if($('script[type="text/html"]#tpl-'+url).length == 0){
            // url = this.default;
        // }
        return url
    },
    init:function(){
        if(!this.container.length) return;
        $(function(){
            PAGE.go()
        })
        window.pageManager = {}
        window.pageManager.go = window.go = function(url){
            location.hash = url;
        }
        window.pageManager.remove = function(url){
            PAGE.remove(url);
        }
        window.pageManager.home = window.home = function(){
            if( PAGE.getUrl() == PAGE.default ){
                return
            }
            PAGE.stack=[];
            PAGE.url=null;
            PAGE.container.html('');
            location.hash = PAGE.default ;
        }
        $(window).on('hashchange', function () {
            PAGE.url=null;
            var url = PAGE.getUrl();
            if(PAGE.exist(url) && PAGE.stack.length > 1 && PAGE.stack[PAGE.stack.length-2].url == url && !(PAGE.stack[PAGE.stack.length-2].dom.hasClass('page-remove') && !PAGE.stack[PAGE.stack.length-1].dom.hasClass('page-remove') ) ){
                PAGE.back();
            }else{
                PAGE.go();
            }
        });
    },
    go:function(){
        $(window).scrollTop(0);
        var url = this.getUrl();
        PAGE.remove(url)
        // $("[page_id='"+url+"']").remove()
        if(!ISMOBILE()){
            $("[page_id]").not("[page_id='"+url+"']").hide();
        }
        var html = this.getHtml(url);
        var dom = $(html).addClass(url).attr("page_id",url);
        this.container.append(dom);
        if(ISMOBILE()){
            // dom.on('animationend webkitAnimationEnd', function(e){
                // dom.removeClass('slideIn').addClass('js_show');
            // });
            if(dom.hasClass('page-tab')){
                // $('.weui-tab').show();
                dom.removeClass('slideIn').addClass('js_show');
                $('.weui-tabbar__item').removeClass('weui-bar__item_on');
                var e = $('a[href="'+location.hash+'"]');
                e.addClass('weui-bar__item_on');
                $('.weui-tabbar i.i').show();
                $('.weui-tabbar i.i+i.i').hide();
                e.find('i.i').hide();
                e.find('i.i+i.i').show();
                $('.weui-tab').css('display','block');
            }else{
                dom.addClass('slideIn')
                setTimeout(function(){
                    dom.removeClass('slideIn').addClass('js_show');
                },300)
                $('.weui-tab').hide();
            }
        }else{
            dom.hide();
            dom.fadeIn(300,function(){
                dom.addClass('js_show');
            })
        }
        if(this.stack.length){
            var old = this.stack[this.stack.length-1]
            old.dom.addClass('slideOutLeft');
            // old.on('animationend webkitAnimationEnd', function(){
                // old.removeClass('slideOutLeft');
            // });
            setTimeout(function(){
                old.dom.removeClass('slideOutLeft');
                if(old.dom.hasClass('page-remove') && ( !ISMOBILE() || !dom.hasClass('page-remove'))){
                    PAGE.remove(old.url);
                }
            },300)
        }
        this.stack.push({url:url,dom:dom});
        if(ISMOBILE()){
            if(!dom.hasClass('page-tab')){
                dom.append($(".footer-xs").html());
            }else{
                dom.append("<div style='height:100px;'></div>");
            }
        }else{
            $('body,html').scrollTop(0)
        }
        PAGE.current = dom;
        dom.trigger("bc-page-success");
    },
    back:function(){
        var old = this.stack.pop();
        if(old.url == this.getUrl()){
            this.go();
            return;
        }
        var old = $('[page_id="'+old.url+'"]');
        if(ISMOBILE()){
            var page_tab = old.hasClass('page-tab');
            if(!page_tab){
                old.addClass('slideOut');
                setTimeout(function(){
                    old.remove();
                    delete old;
                    PAGE.url = null;
                    var url = PAGE.getUrl();
                    // if(ISMOBILE()){
                    // }else{
                    // $("[page_id='"+url+"']").fadeIn(300);
                    // }
                },300)
            }else{
                old.remove();
                delete old;
                PAGE.url = null;
                var url = PAGE.getUrl();
                // if(ISMOBILE()){
                // }else{
                // $("[page_id='"+url+"']").fadeIn(300);
            }
            // old.on('animationend webkitAnimationEnd', function () {
            // })
            if(PAGE.stack.length){
                var back = PAGE.stack[PAGE.stack.length-1].dom
                if(back.hasClass('page-tab')){
                    $('.weui-tab').css('display','block');
                }
                if(page_tab && back.hasClass('page-tab')){
                }else{
                    back.addClass('slideInLeft');
                    // .on('animationend webkitAnimationEnd', function(){
                        // back.removeClass('slideInLeft')
                    // });
                    setTimeout(function(){
                        back.removeClass('slideInLeft');
                    },300)
                }
                PAGE.current = back;
                back.trigger('bc-page-back');
            }
            $('.weui-tabbar__item').removeClass('weui-bar__item_on');
            var e = $('a[href="'+location.hash+'"]');
            e.addClass('weui-bar__item_on');
            $('.weui-tabbar i.i').show();
            $('.weui-tabbar i.i+i.i').hide();
            e.find('i.i').hide();
            e.find('i.i+i.i').show();
        }else{
            old.fadeOut(100,function(){
                old.remove();
                if(PAGE.stack.length){
                    var back = PAGE.stack[PAGE.stack.length-1].dom
                    back.fadeIn(100)
                    PAGE.current = back;
                    back.trigger('bc-page-back');
                }
            })
        }
    },
    remove:function(url){
        if(!url || !url.length) return;
        var stack = null;
        for(var i in this.stack){
            if(url == this.stack[i].url){
                stack = this.stack.splice(i,1)
                stack = stack[0];
                break;
            }
        }
        if(!stack) return;
        stack.dom.remove();
    }
};
EXTRA = {
    init:function(){
        this.fastClick();
        this.androidInputBugFix();
        this.mouse_focus();
        this.preload();
        this.formFobbid();
        this.logout();
        this.inputTextCount();
        this.radioUncheck();
        this.scrollTop();
        this.inputClean();
    },
    inputClean:function(){
        $(document).on('keydown', function(event) {
            $(event.target).parents('.weui-cell').removeClass('weui-cell_warn')
        });
    },
    scrollTop:function(){
        if(ISMOBILE()){
            return;
        }
        var t0 = $(document).scrollTop()||$(window).scrollTop();
        $(document).on('scroll',function(){
            var wd = $(window).height();
            var dh = $(document).height();
            var t = $(document).scrollTop()||$(window).scrollTop();
            $('.bc-scroll-move').each(function(index, el) {
                var e = $(el)
                var url = document.location.href;
                var pattern = /\bhome\b/;
                    str = url;
                if(pattern.test(str)) {
                    var ha = $('.menu-info-heading')[0].offsetHeight;
                    var ca = $('.bc-detail')[0].offsetHeight;
                    var me = $('.menu-info-selected')[0].offsetHeight;
                    var xs = $('.weui-flex-xs')[0].offsetHeight;
                    if ((ha + ca + me + xs) < el.offsetHeight) {
                        return;
                    }
                    if (((ha + ca + me + xs + 326) - el.offsetHeight) <= t0) {
                        if (h <= wd) {
                            var top = 0;
                        }
                        else {
                            var top0 = -(parseInt(e.css('top')) || 0);
                            var topm = h - wd + 50;
                            top = top0 + t - t0;
                            if (top > topm) top = topm;
                            if (top < 0) top = 0;
                        }
                        var pp = {position: 'fixed', top: -top + "px", 'z-index': 999};
                        if (!s) {
                            var w = e.width();
                            if (typeof(Zepto) != 'undefined') w = w - parseInt(e.css('padding-left')) - parseInt(e.css('padding-right'));
                            pp.width = w + "px"
                        }
                        e.addClass('bc-scroll-float');
                        e.css(pp);
                        return;
                    }
                }
                var s = e.attr('style')
                s = s && s.indexOf('position') >=0;
                var o = parseInt(e.attr('offsetTop'));
                if( !o && !s){
                    var o = e.offset().top-parseInt(e.css('margin-top'));e.attr('offsetTop',o)
                }
                var h = e.height()+parseInt(e.css('margin-top'))+parseInt(e.css('margin-bottom'));
                var w;
                if(s&&t<=o){e.removeAttr('style');e.removeClass('bc-scroll-float')}
                if(h+250>dh-(parseInt($('.header').height())||0)-(parseInt($('.footer').height())||0)){if(s){e.removeAttr('style');}}
                else if(t>o){
                    if(h<=wd){var top = 0;}
                    else{
                        var top0 = -(parseInt(e.css('top')) || 0);
                        var topm = h-wd+50;
                        top = top0 + t - t0;
                        if(top > topm) top = topm;
                        if(top < 0 ) top = 0;
                    }
                    var pp = {position:'fixed',top:-top+"px",'z-index':999};
                    if(!s){
                        var w = e.width();
                        if(typeof(Zepto)!='undefined') w = w-parseInt(e.css('padding-left'))-parseInt(e.css('padding-right'));
                        pp.width = w+"px"
                    }
                    e.addClass('bc-scroll-float');
                    e.css(pp);
                }
            });
            t0 = t;
        })
    },
    radioUncheck:function(){
        $(document).on('click', '.bc-radio-uncheck', function(event) {
            event.preventDefault();
            var i = $(this).find('input');
            i.prop('checked',!i.prop('checked')).trigger('change');
        });
    },
    inputTextCount:function(){
        $(document).on("keyup paste","input,textarea",function(){
            var c = $(this).next(".weui-textarea-counter")
            if(c){
                var l = parseInt($(this).val().replace(/[^x00-xFF]/g,'**').length);
                var m = parseInt(c.find("max").html())
                c.find("span").html(l);
                if( l > m ){
                    c.css({color:"maroon"})
                }else{
                    c.css({color:"inherit"})
                }
            }
        })
        $(document).on('bc-value-write', 'textarea', function(event) {
            var c = $(this).next(".weui-textarea-counter")
            if(c){
                var l = parseInt($(this).val().replace(/[^x00-xFF]/g,'**').length);
                var m = parseInt(c.find("max").html())
                c.find("span").html(l);
                if( l > m ){
                    c.css({color:"maroon"})
                }else{
                    c.css({color:"inherit"})
                }
            }
        });
    },
    logout:function(){
        // if(WEIXIN.is()){$("#logout").remove();return}
        $(document).on('click', '#logout', function(event) {
            if(!confirm("确认退出登录？")) return;
            event.preventDefault();
            $.ajax({
                url: '/logout',
                xhrFields:{
                    withCredentials:true
                },
                success:function(ret){
                    if(!ret.state) retur
                    // TOAST.success("成功安全退出",1)
                    $(document).trigger("bc-logout-success");
                    $(document).trigger("logout-success");
                    location.reload();
                }
            })
        });
    },
    formFobbid:function(){
        $(document).on('submit', 'form', function(event) {
            event.preventDefault();
            var s = $(this).attr('submit');
            if(s) $(s).trigger('click');
        });
    },
    fastClick:function(){
        var supportTouch = function(){
            try {
                document.createEvent("TouchEvent");
                return true;
            } catch (e) {
                return false;
            }
        }();
        var _old$On = $.fn.on;

        $.fn.on = function(){
            if(/click/.test(arguments[0]) && typeof arguments[1] == 'function' && supportTouch){ // 只扩展支持touch的当前元素的click事件
                var touchStartY, callback = arguments[1];
                _old$On.apply(this, ['touchstart', function(e){
                    touchStartY = e.changedTouches[0].clientY;
                }]);
                _old$On.apply(this, ['touchend', function(e){
                    if (Math.abs(e.changedTouches[0].clientY - touchStartY) > 10) return;

                    e.preventDefault();
                    callback.apply(this, [e]);
                }]);
            }else{
                _old$On.apply(this, arguments);
            }
            return this;
        };
    },
    androidInputBugFix:function (){
        // .container 设置了 overflow 属性, 导致 Android 手机下输入框获取焦点时, 输入法挡住输入框的 bug
        // 相关 issue: https://github.com/weui/weui/issues/15
        // 解决方法:
        // 0. .container 去掉 overflow 属性, 但此 demo 下会引发别的问题
        // 1. 参考 http://stackoverflow.com/questions/23757345/android-does-not-correctly-scroll-on-input-focus-if-not-body-element
        //    Android 手机下, input 或 textarea 元素聚焦时, 主动滚一把
        if (/Android/gi.test(navigator.userAgent)) {
            window.addEventListener('resize', function () {
                if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
                    window.setTimeout(function () {
                        document.activeElement.scrollIntoViewIfNeeded();
                    }, 0);
                }
            })
        }
    },
    mouse_focus:function(){
        $(document).on('mouseover click', '.bc-input-focus', function(event) {
            $(this).select();
            $(this).find('input,textarea').focus();
            event.preventDefault();
        });
    },
    preload:function(){
        return
        $(document).on("load", function(){
            var imgList = [
            // "./images/layers/content.png",
            // "./images/layers/navigation.png",
            // "./images/layers/popout.png",
            // "./images/layers/transparent.gif"
            ];
            for (var i = 0, len = imgList.length; i < len; ++i) {
                new Image().src = imgList[i];
            }
        });
    }
};
WEIXIN = {
    is:function(){
        return (window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger')
    },
    init:function(){
        if(!WEIXIN.is()) return;
        document.write('<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>');
        $.getJSON('/wechat/jsapi?url=' + encodeURIComponent(location.href), function (res) {
            wx.config({
                // beta: true,
                // debug: true ,
                appId: res.appId ,
                timestamp: res.timestamp ,
                nonceStr: res.nonceStr ,
                signature: res.signature ,
                jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] ,
            });
            wx.ready(function () {
                $(document).trigger('bc-wechat-ready');
                WEIXIN.share($('.page'));
                $(document).on('bc-page-success bc-view-success bc-page-back bc-info-success bc-list-success', function(event) {
                    var e = $(event.target);
                    if(e.hasClass('bc-info')&&!e.find('.wechat-title').length) return;
                    if(e.hasClass('bc-list')&&!e.find('.wechat-title').length) return;
                    WEIXIN.share(e);
                });
            });
        });
    },
    login:function(){
        if(!WEIXIN.is()) return;
        $('body').html('');
        TOAST.stop();
        TOAST.load("微信安全登陆",1);
        url=window.location.pathname+window.location.hash
        url='/wechat/redirect?url='+url.replace("#","{XXXXX}")
        location.href=url
    },
    share:function(e){
        var title = $('title').html();
        var desc = "";
        var imgurl = $('logo').html();
        e.find('.wechat-imgurl').each(function(index, el) {
            if($(el).attr('src')){
                imgurl = $(el).attr('src');
                return false;
            }
        });
        e.find('.wechat-desc').each(function(index, el) {
            if($(el).text()){
                desc = $(el).text();
                return false;
            }
        });
        e.find('.wechat-title').each(function(index, el) {
            if($(el).text()){
                title = $(el).text()+" - "+$('title').html();
                return false;
            }
        });
        var s = {title:title,desc:desc,imgurl:imgurl};
        if(!WEIXIN.is()) return;
        wx.onMenuShareTimeline({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分享图标
        });
        wx.onMenuShareAppMessage({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分享图标
        });
        wx.onMenuShareQQ({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分
        });
        wx.onMenuShareWeibo({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分
        });
        wx.onMenuShareQZone({
            title: s.title, // 分享标题
            desc: s.desc, // 分享标题
            link: window.location.href, // 分享链接
            imgUrl: s.imgurl, // 分
        });

    }
};
BTN_GROUP = {
    init:function(){
        var self = this;
        $(document).on('bc-value-write', '.bc-btn-group input.bc-btn-group-value', function(event) {
            self.select(this);
        });
        $(document).on('bc-rank-success', '.bc-btn-group .bc-rank,.bc-btn-group.bc-rank', function(event) {
            self.select(this);
        });
        $(document).on('change', '.bc-btn-group .bc-btn-group-btns', function(event) {
            self.put(this);
        });
    },
    put:function(e){
        e = $(e).closest('.bc-btn-group');
        if(!e.length) return;
        var value = [];
        e.find('.bc-btn-group-btns input:checked').each(function(index, el) {
            var v = $(el).val()
            if(v) value.push(v);
        });
        value = value.join(',');
        var target = e.attr("data-target");
        if($(target).length){
            $(target).val(value).trigger('change');
        }
        var input = e.find('input.bc-btn-group-value');
        if($(input).length) input.val(value).trigger('change');
    },
    select:function(e){
        e = $(e).closest('.bc-btn-group');
        if(!e.length) return;
        var value = e.find('input.bc-btn-group-value');
        value = value.length?value.val():'';
        var target = e.attr("data-target");
        if($(target).length){
            $(target).val(value).trigger('change');
        }
        var v = value.split(",");
        var vv = {}
        for(var i in v){
            vv[v[i]] = 1;
        }
        e.find('.bc-btn-group-btns input').each(function(index, el) {
            var v = $(el).val();
            if(v && vv[v]){
                $(el).prop('checked',true);
            }else{
                $(el).prop('checked',false);
            }
        });
    }
};
IMAGE = {
    start:function(){
        $('.bc-img').each(function(index, el) {
            IMAGE.init(el);
        });
        $(document).on('bc-page-success bc-view-success', function(event) {
            var e = $(event.target);
            e.find('.bc-img').each(function(index, el) {
                IMAGE.init(el);
            });
        });
        $(document).on('bc-value-write', '.bc-img .bc-img-urls', function(event) {
            IMAGE.group.set(this);
        });
        $(document).on('click', '.bc-img-remove:not(.disabled)', function(event) {
            if(!confirm('确认删除一张图片？')) return;
            IMAGE.group.remove(this);
        });
        $(document).on('click', '.bc-img-remove-all', function(event) {
            if(!confirm('确认删除全部图片？')) return;
            IMAGE.group.removeAll(this);
        });
    },
    input:function(e){
        var ret = {}
        e.find(".bc-img-input").each(function(index, el) {
            ret[$(el).attr('name')] = $(el).val();
        });
        // console.log(ret);
        return ret;
    },
    group:{
        put:function(e){
            var e = $(e).closest('.bc-img');
            if(!e.length) return;
            var input = e.find('.bc-img-urls');
            var urls = [];
            e.find('.bc-img-content url').each(function(index, el) {
                urls.push($(el).html());
            });
            urls = urls.join(',');
            input.val(urls).trigger('change');
            IMAGE.count(e);
        },
        set:function(e){
            var e = $(e).closest('.bc-img');
            if(!e.length) return;
            e.find('.bc-img-content').remove();
            var urls = e.find('.bc-img-urls');
            if(!urls.length) return;
            var v = urls.val();
            IMAGE.count(e);
            if(!v) return;
            v = v.split(",");
            var template = e.find('.bc-img-template')
            template.hide();
            var t = template.prop('outerHTML');
            for(var i in v){
                var url = v[i];
                template.parent().append(t);
                var newline = template.parent().children().last();
                newline.removeClass('bc-img-template');
                newline.addClass('bc-img-content');
                newline.fadeIn();
                newline.append('<url class="hidden">'+url+'</url>');
                newline.css('background-image','url('+url+')');
            }
            IMAGE.count(e);
        },
        remove:function(e){
            var el = $(e).closest('.bc-img-content');
            if(!el.length) return;
            var e = $(e).closest('.bc-img');
            if(!e.length) return;
            el.fadeOut(120,function(){
                el.remove();
                IMAGE.group.put(e);
            })
        },
        removeAll:function(e){
            // var el = $(e).closest('.bc-img-content');
            // if(!el.length) return;
            var e = $(e).closest('.bc-img');
            if(!e.length) return;
            e.find('.bc-img-content').fadeOut(120,function(){
                e.find('.bc-img-content').remove();
                IMAGE.group.put(e);
            })
        }
    },
    upload:{
        success:function(e,res,img_new){
            var url = res.data.url;
            img_new.trigger("img-success",res);
            img_new.trigger("bc-img-success",res);
            img_new.find('.bc-img-progress').remove();
            img_new.css("background-image","url("+url+")");
            img_new.removeClass('weui-uploader__file_status')
            img_new.find('.weui-loading').remove();
            img_new.append('<url class="hidden">'+url+'</url>');
            IMAGE.group.put(e);
        },
        error:function(e,errormsg,img_new){
            img_new.find('.bc-img-progress').remove();
            img_new.find(".weui-uploader__file-content").html('<i class="weui-icon weui-icon-warn"><br/><small>'+errormsg+'</small></i>')
            ERROR.top("上传",errormsg);
        },
        ajax:function(img_new,url,formData){
            var ee = img_new;
            var xhrOnProgress=function(fun) {
                xhrOnProgress.onprogress = fun; //绑定监听
                //使用闭包实现监听绑
                return function() {
                    //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
                    var xhr = $.ajaxSettings.xhr();
                    //判断监听函数是否为函数
                    if (typeof xhrOnProgress.onprogress !== 'function')
                        return xhr;
                    //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
                    if (xhrOnProgress.onprogress && xhr.upload) {
                        xhr.upload.onprogress = xhrOnProgress.onprogress;
                    }
                    return xhr;
                }
            }
            $.ajax({
                url: url,
                type: "POST" ,

                xhr:xhrOnProgress(function(event){
                    var percent= parseInt(100 * event.loaded / event.total);//计算百分比
                    if(percent >= 100){
                        percent = '<small>正在处理</small>';
                    }else{
                        percent = percent+"%"
                    }
                    img_new.find('.bc-img-progress').html(percent);
                    // console.log(percent)
                }),
                data: formData ,
                // dataType: "json",
                enctype: 'multipart/form-data',
                // async: true,
                //要想用jquery的ajax来提交FormData数据,
                //则必须要把这两项设为false
                xhrFields:{
                    withCredentials:true
                },
                cache:false,
                processData: false,
                contentType: false,
                //这里是防表单重复提交,可以忽略
                // beforeSend: function(xhr){
                    // $("#importForm :submit").attr("disabled","disabled");
                // },
                complete: function(xhr,status){
                    // $("#uploaderInput").val('')
                },
                error: function(xhr,status,error){
                    IMAGE.upload.error(ee,xhr.status,img_new);
                    // console.log(xhr,status);
                    // alert("请求出错!");
                },
                success: function(res){
                    // if(typeof(res) == 'object'){res = JSON.stringify(res)}
                    // console.log(res)
                    if(!res.state){
                        IMAGE.upload.error(ee,res.errormsg,img_new)
                        // alert(res.errormsg);
                        return;
                    }
                    IMAGE.upload.success(ee,res,img_new);
                    // image.group.set(ee);
                    // alert('ok');
                }
            });
        }
    },
    count:function(e){
        var e = $(e).closest('.bc-img')
        var img_count = e.find(".bc-img-content").length;
        var img_max = parseInt(e.find('.weui-uploader__max').text());
        e.find('.weui-uploader__count').text(img_count);
        if(img_count>=img_max){
            e.find('.weui-uploader__count').css('color','maroon');
            e.find('.weui-uploader__input-box').hide();
        }else{
            e.find('.weui-uploader__count').removeAttr('style');
            e.find('.weui-uploader__input-box').fadeIn();
        }
    },
    init:function(e){
        var self = this;
        var e       = $(e);
        var tmpl    = e.find(".bc-img-template").prop('outerHTML');
        var input   = e.find('.weui-uploader__input');
        var imgs    = e.find(".weui-uploader__files");
        $('.bc-img-template').hide();
        e.find('.bc-img-template').each(function(index, el) {
            var p = $(el).parent();
            if(p.hasClass('bc-img-sortable')){
                Sortable.create(p.get(0),{
                    animation: 150,
                    scrollSensitivity: 100,
                    onUpdate:function(evt){
                        IMAGE.group.put(evt.item);
                    }
                })
            }
        });
        input.on("change", function(event){
            //获取参数
            var data = IMAGE.input(e);
            var data_s = [];
            for(var j in data){
                data_s.push(j+"="+data[j]);
            }
            url_s = data_s.length?"?"+data_s.join("&"):"";
            var port_value = e.attr("data-port-value");
            if(port_value){try{port_value = eval(port_value);}catch(e){port_value=null};}
            var url = port_value || e.attr("data-port")
            if(!url){
                console.error("BC-IMG PORT TEST",e);
                url = "/test/upload";
            }
            url = url + url_s;
            console.log('BC-IMG UPLOAD',e,url)
            var src, urlLocal = window.URL || window.webkitURL || window.mozURL, files = event.target.files;
            var img_max = parseInt(e.find('.weui-uploader__max').text());
            var count = e.find('.weui-uploader__count');
            var img_count = e.find(".bc-img-content").length;
            for (var i = 0, len = files.length; i < len; ++i) {
                if(img_count >= img_max){
                    ERROR.top("上传","数量达最大值");
                    count.html(img_count);
                    count.css("color","maroon");
                    break;
                }
                img_count += 1
                count.html(img_count);
                count.removeAttr('style');

                var file = files[i];
                // console.log(files);

                if (urlLocal) {
                    src = urlLocal.createObjectURL(file);
                } else {
                    src = event.target.result;
                }

                // imgs.append(tmpl.replace(/bc-img-template/g,'bc-img-content'));
                imgs.append(tmpl);
                var img_new = imgs.children().last();
                img_new.css('background-image',"url("+src+")");
                img_new.addClass('bc-img-content');
                img_new.removeClass('bc-img-template');
                // console.log(img_new);
                img_new.addClass('weui-uploader__file_status')
                img_new.find('.weui-uploader__file-content').append("<i class='weui-loading'></i><span class='bc-img-progress'></span>")
                img_new.fadeIn();
                //为FormData对象添加数据
                //创建FormData对象
                var formData = new FormData();
                $.each(input[0].files, function(ii, ff) {
                    if(i == ii){
                        formData.append(0, ff);
                    }
                });
                //
                IMAGE.upload.ajax(img_new,url,formData);
            }
            input.val('');
            // $("#img_uploader_form").serialize();
        });
        $(document).on('click', '.weui-uploader__file', function(event) {
            if($(this).find(".weui-icon-warn").length){
                var t = $(this)
                t.fadeOut(100,function(){
                    t.remove()
                })
            }
            event.preventDefault();
        });
    }
};
VIEW = {
    init:function(){
        $(document).on('bc-page-success', '.page', function() {
            VIEW.reload($(this).find('.bc-view'));
        });
        $(document).on('click', '.bc-view-error', function() {
            VIEW.reload(this);
        });
    },
    reload:function(v){
        $(v).each(function(index, el) {
            VIEW._reload($(el));
        });
    },
    template:{
        loading:"<div class='bc-view-loading' style='padding:250px 0;text-align:center'><span class='weui-loading'></span> 正在加载页面... </div>",
        error:"<div class='bc-view-error' style='padding:200px 0;color:maroon;text-align:center'><p mute><i style='font-size:48px;' class='i i-refresh_light'></i><br/>页面错误，点击刷新</p>ERRORMSG</div>"
    },
    _reload:function(v){
        var template = this.template;
        var v = $(v).closest('.bc-view');
        if(!v.length) return;
        if(v.hasClass('bc-view-loading')||v.hasClass('bc-view-loaded')) return;
        var port_value = v.attr("data-port-value");
        if(port_value){try{port_value = eval(port_value);}catch(e){port_value=null};}
        var url = port_value || v.attr('data-port');
        if(!url){
            url = '/test/view';
            console.error('BC-VIEW TEST-PORT',v);
        }
        v.html(template.loading);
        $.ajax({
            url:url,
            xhrFields:{
                withCredentials:true
            },
            success:function(text){
                v.html(text.replace(/sss>/g,'script>'));
                v.removeClass('bc-view-loading');
                v.addClass('bc-view-loaded');
                console.log('BC-VIEW SUCCESS',v);
                v.trigger("bc-view-success");
            },
            error:function(xhr){
                var errormsg = xhr.statusText + " " + xhr.status ;
                v.html(template.error.replace('ERRORMSG',errormsg));
                v.removeClass('bc-view-loading');
                v.trigger("bc-view-error",errormsg);
            }
        })
    }
};
DISTRICT = {
    init:function(){
        $('.bc-district').each(function(index, el) {
            DISTRICT.load(el);
        });
        $(document).on('bc-view-success bc-page-success', function(event) {
            $(event.target).find('.bc-district').each(function(index, el) {
                DISTRICT.load(el);
            });
        });
    },
    data:null,
    load:function(e){
        var self = this;
        var e = $(e).closest('.bc-district');
        if(!e.length || e.hasClass('bc-district-active')) return;
        if(self.data){
            self._load(e);
        }else{
            $.ajax({
                url: '/js/bc-district.json',
                xhrFields:{
                    withCredentials:true
                },
                success:function(res){
                    self.data = res;
                    self._load(e);
                }
            })

        }
    },
    _load:function(el){
        var p = el.find('select[name="province"]');
        var c = el.find('select[name="city"]');
        var d = el.find('select[name="district"]');
        var data = this.data;
        p.append("<option value='' selected='selected'>选择省/市</option>");
        c.append("<option value='' selected='selected'>选择市/区</option>");
        d.append("<option value='' selected='selected'>选择区/县</option>");
        el.addClass('bc-district-active');
        for(var i in data){
            var dd = data[i];
            p.append("<option value='"+dd.name+"'>"+dd.name+"</option>");
        }
        var v = p.attr('value');
        c.on('change bc-district-select bc-value-write',function() {
            var cc = [];
            for(var i in data){
                if(p.val() == data[i].name){
                    cc = data[i].city
                    break;
                }
            }
            var dd = [];
            for(var j in cc){
                if(c.val() == cc[j].name){
                    dd = cc[j].district;
                    break;
                }
            }
            d.html("<option value='' selected='selected'>选择区/县</option>");
            // d.trigger('change');
            for(var i in dd){
                d.append("<option value='"+dd[i]+"'>"+dd[i]+"</option>");
            }
            var v = d.attr('value');
            if(v){d.val(v);d.removeAttr('value')};
        });
        p.on('change bc-district-select bc-value-write',function() {
            c.html("<option value='' selected='selected' >选择市/区</option>");
            d.html("<option value=''  selected='selected'>选择区/县</option>");
            for(var i in data){
                if(p.val() == data[i].name){
                    var cc = data[i].city;
                    break;
                }
            }
            for(var i in cc){
                c.append("<option value='"+cc[i].name+"'>"+cc[i].name+"</option>");
            }
            var v = c.attr('value');
            if(v){c.val(v);c.trigger('bc-district-select');c.removeAttr('value')}
        });
        if(v){p.val(v);p.trigger('bc-district-select');p.removeAttr('value')}
    }
};
COOKIE.init();
WEIXIN.init();
LANG.init();
$(function(){
    VIEW.init();
    INFO.init();
    LIST.init();
    DETAIL.init();
    RANK.init();
    MODAL.init();
    IMAGE.start();
    TAB.init();
    PAGE.init();
    EXTRA.init();
    BTN_GROUP.init();
    DISTRICT.init();
});

(function ($) {
    var Tab = function (tab) {
        var _this = this;
        this.tab = tab;
        // 默认配置参数
        this.config = {
            "triggerType": "mouseover",
            "effect": "default"
        };
        if (this.getConfig()) {
            $.extend(this.config, this.getConfig());
        }
        // 标签列表,内容列表
        this.tabTitems = this.tab.find('ul.tab-nav li');
        this.contentItems = this.tab.find('div.content-wrap div.content-item');
        // 保存配置参数
        var config = this.config;
        if(config.triggerType === 'click') {
            // this.tabTitems.bind(config.triggerType, function() {
            //     _this.invoke($(this));
            // });
            $('body').on('click', 'ul.tab-nav li', function() {
                _this.invoke($(this));
            })
        } else if (config.triggerType === 'mouseover' || config.triggerType != 'click') {
            this.tabTitems.bind('mouseover', function() {
                _this.invoke($(this));
            })
        };
    }
    Tab.prototype = {
        getConfig: function () {
            var config = this.tab.attr('data-config');
            if (config && config != null) {
                return JSON.parse(config);
            } else {
                return null;
            }
        },
        // 事件驱动函数
        invoke: function(currentTab) {
            var _this = this;
            var index = currentTab.index();
            // tab选中状态
            currentTab.addClass('actived').siblings().removeClass('actived');
            // 切换内容区域
            var effect = this.config.effect;
            var contentItems = this.contentItems;
            if(effect === 'default') {
                contentItems.eq(index).addClass('current').siblings().removeClass('current');
            } else if(effect === 'fade') {
                contentItems.eq(index).fadeIn().siblings().fadeOut();
            }
        }
    };
    Tab.init = function(tabs) {
        var _this = this;
        tabs.each(function() {
            new _this($(this));
        });
    }
    window.Tab = Tab;
})($);